<template>
  <div class="destiny-calculator">


    <div class="calculator-container">
      <div class="input-section">
        <div class="input-group">
          <label class="input-label">姓名</label>
          <input v-model="userData.name" type="text" class="destiny-input" placeholder="请输入中文姓名" />
          <div v-if="userData.name && !/^[\u4e00-\u9fa5]+$/.test(userData.name)" class="error-text">
            请输入有效的中文姓名
          </div>
        </div>

        <div class="input-group">
          <label class="input-label">日历类型</label>
          <div class="calendar-selector">
            <button @click="calendarType = 'YANG_LI'" :class="['calendar-btn', { active: calendarType === 'YANG_LI' }]">
              <span class="btn-text">阳历</span>
            </button>
            <div class="calendar-divider"></div>
            <button @click="calendarType = 'NONG_LI'" :class="['calendar-btn', { active: calendarType === 'NONG_LI' }]">
              <span class="btn-text">农历</span>
            </button>
          </div>
        </div>

        <div class="date-grid">
          <div class="input-group">
            <label class="input-label">出生年份</label>
            <input v-model="userData.birthYear" class="destiny-input" placeholder="2000" min="1990" max="2100" />
            <div
              v-if="userData.birthYear && !(Number.isFinite(parseInt(userData.birthYear)) && parseInt(userData.birthYear) > 1900 && userData.birthYear < 2100)"
              class="error-text">
              年份必须在1990-2100之间
            </div>
          </div>

          <div class="input-group">
            <label class="input-label">出生月份</label>
            <input v-model="userData.birthMonth" class="destiny-input" placeholder="12" min="1" max="12" />
            <div
              v-if="userData.birthMonth && !(Number.isFinite(parseInt(userData.birthMonth)) && parseInt(userData.birthMonth) > 0 && userData.birthMonth < 13)"
              class="error-text">
              月份必须在1-12之间
            </div>
          </div>

          <div class="input-group">
            <label class="input-label">出生日期</label>
            <input v-model="userData.birthDay" class="destiny-input" placeholder="1" min="1" max="31" />
            <div
              v-if="userData.birthDay && !(Number.isFinite(parseInt(userData.birthDay)) && parseInt(userData.birthDay) > 0 && parseInt(userData.birthDay) <32)"
              class="error-text">
              日期必须在1-31之间
            </div>
          </div>
          <div v-if="calendarType === 'NONG_LI'" class="input-group">
            <label class="input-label">是否闰月</label>
            <select v-model="userData.isLeapMonth" class="destiny-select">
              <option :value="false">正常月份</option>
              <option :value="true">闰月</option>
            </select>
          </div>
        </div>

        <div class="input-group">
          <label class="input-label">出生时辰</label>
          <select v-model="userData.birthHour" class="destiny-select">
            <option value="">请选择时辰</option>
            <option value="23:00-01:00">子时 (23:00-01:00)</option>
            <option value="01:00-03:00">丑时 (01:00-03:00)</option>
            <option value="03:00-05:00">寅时 (03:00-05:00)</option>
            <option value="05:00-07:00">卯时 (05:00-07:00)</option>
            <option value="07:00-09:00">辰时 (07:00-09:00)</option>
            <option value="09:00-11:00">巳时 (09:00-11:00)</option>
            <option value="11:00-13:00">午时 (11:00-13:00)</option>
            <option value="13:00-15:00">未时 (13:00-15:00)</option>
            <option value="15:00-17:00">申时 (15:00-17:00)</option>
            <option value="17:00-19:00">酉时 (17:00-19:00)</option>
            <option value="19:00-21:00">戌时 (19:00-21:00)</option>
            <option value="21:00-23:00">亥时 (21:00-23:00)</option>
          </select>
        </div>

        <button @click="calculateFiveElements" 
          class="destiny-button"
          :class="{ 'loading': isLoading, 'pulsing': !isLoading }" 
          :disabled="isLoading || !isFormValid"
          :title="disabledTooltip">
          <span class="button-text" v-if="!isLoading">计算五行</span>
          <span class="button-text" v-else>计算中...</span>
        </button>
      </div>

      <!-- 优化后的结果展示区域 -->
      <div v-if="fiveElementsResult" class="result-section">
        <!-- 个人信息卡片 -->
        <div class="info-card">
          <h2 class="card-title">📋 个人信息</h2>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">姓名：</span>
              <span class="info-value">{{ fiveElementsResult.personalInfo.name }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">阳历生日：</span>
              <span class="info-value">{{ fiveElementsResult.personalInfo.solarBirthday }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">农历生日：</span>
              <span class="info-value">{{ fiveElementsResult.personalInfo.lunarBirthday }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">生肖：</span>
              <span class="info-value">{{ fiveElementsResult.personalInfo.zodiac }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">星座：</span>
              <span class="info-value">{{ fiveElementsResult.personalInfo.constellation }}</span>
            </div>
          </div>
        </div>

        <!-- 姓名五行卡片 -->
        <div class="element-card">
          <h2 class="card-title">🪷 姓名五行</h2>
          <div class="name-elements-grid">
            <div v-for="(item, index) in fiveElementsResult.nameElements" :key="index" class="name-element-item">
              <span class="character">{{ item.char }}</span>
              <span class="element-badge" :class="item.element">{{ item.element }}</span>
            </div>
          </div>
        </div>

        <!-- 修改生辰八字五行卡片 -->
        <div class="element-card">
          <h2 class="card-title">📅 生辰八字五行</h2>
          <!-- 替换现有的生辰八字五行展示部分 -->
          <div class="bazi-elements">
            <div class="bazi-row">
              <div class="bazi-cell">
                <span class="bazi-label">年柱</span>
                <div class="bazi-content">
                  <span class="bazi-char">{{ fiveElementsResult.bazi.yearStem }}{{ fiveElementsResult.bazi.yearBranch
                    }}</span>
                  <div class="element-pair">
                    <span class="element-badge" :class="wuxing(fiveElementsResult.bazi.yearStem)">
                      天干: {{ wuxing(fiveElementsResult.bazi.yearStem) }}
                    </span>
                    <span class="element-badge" :class="wuxing(fiveElementsResult.bazi.yearBranch)">
                      地支: {{wuxing(fiveElementsResult.bazi.yearBranch)}}
                    </span>
                  </div>
                </div>
              </div>
              <div class="bazi-cell">
                <span class="bazi-label">月柱</span>
                <div class="bazi-content">
                  <span class="bazi-char">{{ fiveElementsResult.bazi.monthStem }}{{ fiveElementsResult.bazi.monthBranch
                    }}</span>
                  <div class="element-pair">
                    <span class="element-badge" :class="wuxing(fiveElementsResult.bazi.monthStem)">
                      天干: {{ wuxing(fiveElementsResult.bazi.monthStem) }}
                    </span>
                    <span class="element-badge" :class="wuxing(fiveElementsResult.bazi.monthBranch)">
                      地支: {{ wuxing(fiveElementsResult.bazi.monthBranch) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div class="bazi-row">
              <div class="bazi-cell">
                <span class="bazi-label">日柱</span>
                <div class="bazi-content">
                  <span class="bazi-char">{{ fiveElementsResult.bazi.dayStem }}{{ fiveElementsResult.bazi.dayBranch
                    }}</span>
                  <div class="element-pair">
                    <span class="element-badge" :class="wuxing(fiveElementsResult.bazi.dayStem)">
                      天干: {{ wuxing(fiveElementsResult.bazi.dayStem) }}
                    </span>
                    <span class="element-badge" :class="wuxing(fiveElementsResult.bazi.dayBranch)">
                      地支: {{ wuxing(fiveElementsResult.bazi.dayBranch) }}
                    </span>
                  </div>
                </div>
              </div>
              <div class="bazi-cell">
                <span class="bazi-label">时柱</span>
                <div class="bazi-content">
                  <span class="bazi-char">{{ fiveElementsResult.bazi.hourStem }}{{ fiveElementsResult.bazi.hourBranch
                    }}</span>
                  <div class="element-pair">
                    <span class="element-badge" :class="wuxing(fiveElementsResult.bazi.hourStem)">
                      天干: {{ wuxing(fiveElementsResult.bazi.hourStem) }}
                    </span>
                    <span class="element-badge" :class="wuxing(fiveElementsResult.bazi.hourBranch)">
                      地支: {{ wuxing(fiveElementsResult.bazi.hourBranch) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 修改五行统计表格 -->
        <!-- 修改五行统计表格 -->
        <div class="stats-card">
          <h2 class="card-title">📊 五行统计</h2>
          <div class="stats-table">
            <table>
              <thead>
                <tr>
                  <th>五行</th>
                  <th>姓名</th>
                  <th>年柱</th>
                  <th>月柱</th>
                  <th>日柱</th>
                  <th>时柱</th>
                  <th>总计</th>
                  <th width="80px">评级</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="element in fiveElements" :key="element">
                  <td>
                    <span class="element-badge" :class="element">{{ element }}</span>
                  </td>
                  <td>
                    <span class="count-text">{{ fiveElementsResult.elementStats[element].nameCount || '' }}</span>
                  </td>
                  <td>
                    <span class="element-char">
                      {{ wuxing(fiveElementsResult.bazi.yearStem) === element ? fiveElementsResult.bazi.yearStem : '' }}
                      {{ wuxing(fiveElementsResult.bazi.yearBranch) === element ? fiveElementsResult.bazi.yearBranch :
                      '' }}
                    </span>
                  </td>
                  <td>
                    <span class="element-char">
                      {{ wuxing(fiveElementsResult.bazi.monthStem) === element ? fiveElementsResult.bazi.monthStem : ''
                      }}
                      {{ wuxing(fiveElementsResult.bazi.monthBranch) === element ? fiveElementsResult.bazi.monthBranch :
                      '' }}
                    </span>
                  </td>
                  <td>
                    <span class="element-char">
                      {{ wuxing(fiveElementsResult.bazi.dayStem) === element ? fiveElementsResult.bazi.dayStem : '' }}
                      {{ wuxing(fiveElementsResult.bazi.dayBranch) === element ? fiveElementsResult.bazi.dayBranch : ''
                      }}
                    </span>
                  </td>
                  <td>
                    <span class="element-char">
                      {{ wuxing(fiveElementsResult.bazi.hourStem) === element ? fiveElementsResult.bazi.hourStem : '' }}
                      {{ wuxing(fiveElementsResult.bazi.hourBranch) === element ? fiveElementsResult.bazi.hourBranch :
                      '' }}
                    </span>
                  </td>
                  <td>
                    <span class="total-count">{{ fiveElementsResult.elementStats[element].count }}</span>
                  </td>
                  <td>
                    <span
                      :class="['strength-rating', getStrengthRating(fiveElementsResult.elementStats[element].count)]">
                      {{ getStrengthRating(fiveElementsResult.elementStats[element].count) }}
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 命理解析 -->
        <div class="analysis-card">
          <h2 class="card-title">🔮 AI命理解析</h2>
          <button v-if="!isStreaming && !streamingAnalysis" @click="startAIAnalysis" class="ai-analysis-btn"
            :disabled="!fiveElementsResult">
            <span class="btn-text">开始AI命理解析</span>
            <div class="button-glow"></div>
          </button>

          <div v-if="isStreaming" class="streaming-indicator">
            <div class="typing-animation">AI正在分析中...</div>
          </div>

          <div class="analysis-content markdown-content" v-if="streamingAnalysis"
            v-html="renderMarkdown(streamingAnalysis)"></div>

          <button v-if="streamingAnalysis && !isStreaming" @click="resetAnalysis" class="ai-analysis-btn secondary">
            <span class="btn-text">重新解析</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted,nextTick } from 'vue';
import request from '../http/request';
import MarkdownIt from 'markdown-it';

// 创建Markdown解析器实例
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
});

// 用户输入数据
const userData = reactive({
  name: '',
  birthYear: null,
  birthMonth: null,
  isLeapMonth: false,
  birthDay: null ,
  birthdayType: '',
  birthHour: '',
  shiChen: ''
})

// 添加计算按钮禁用状态
const isFormValid = computed(() => {
  // 验证姓名：必须包含中文字符
  const isValidName = userData.name && /^[\u4e00-\u9fa5]+$/.test(userData.name);
  // 验证年份：必须在1900-2100之间
  const year = parseInt(userData.birthYear);
  const isValidYear = userData.birthYear && Number.isFinite(year) && year >= 1900 && year <= 2100;
  // 验证月份：必须在1-12之间
  const month = parseInt(userData.birthMonth);
  const isValidMonth = userData.birthMonth && Number.isFinite(month) && month >= 1 && month <= 12;
  // 验证日期：必须在1-31之间
  const day = parseInt(userData.birthDay);
  const isValidDay = userData.birthDay && Number.isFinite(day) && day >= 1 && day <= 31;
  // 验证时辰：必须已选择
  const isValidHour = userData.birthHour;
  return (
    isValidName &&
    isValidYear &&
    isValidMonth &&
    isValidDay &&
    isValidHour
  );
});

// 添加loading状态
const isLoading = ref(false);

// 五星结果
const fiveElementsResult = ref(null)
const calendarType = ref('YANG_LI')

// 添加流式分析相关状态
// 在脚本部分添加新的响应式变量和方法
const streamingAnalysis = ref('')
const isStreaming = ref(false)
const eventSource = ref(null)

// 天干地支数据
const fiveElements = ['金', '木', '水', '火', '土']

const hourToBranch = {
  '23:00-01:00': '子', '01:00-03:00': '丑', '03:00-05:00': '寅',
  '05:00-07:00': '卯', '07:00-09:00': '辰', '09:00-11:00': '巳',
  '11:00-13:00': '午', '13:00-15:00': '未', '15:00-17:00': '申',
  '17:00-19:00': '酉', '19:00-21:00': '戌', '21:00-23:00': '亥'
}

// 在script setup部分添加强度评级函数
const getStrengthRating = (count) => {
  if (count <= 1) return '偏弱';
  if (count === 2 || count === 3) return '适中';
  return '偏强';
};

// 添加AI分析函数
const startAIAnalysis = () => {
  if (!fiveElementsResult.value) return
  
  isStreaming.value = true
  streamingAnalysis.value = ''
  
  // 构建分析消息
  const analysisMessage = generateAnalysisPrompt()
  
  // 创建EventSource连接
  const url = `${import.meta.env.VITE_API_URL}/wuxing/ai/generateStream?message=${encodeURIComponent(analysisMessage)}`
  eventSource.value = new EventSource(url)

  // 修改EventSource消息处理
  eventSource.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      const text = data.result?.output?.text || '';
      if (text) {
        processStreamingData(text);
      }
    } catch (e) {
      console.error('解析流数据失败:', e);
    }
  };
  
  eventSource.value.onerror = (error) => {
    console.error('流连接错误:', error)
    isStreaming.value = false
    if (eventSource.value) {
      eventSource.value.close()
    }
  }
  
  eventSource.value.addEventListener('done', () => {
    isStreaming.value = false
    if (eventSource.value) {
      eventSource.value.close()
    }
  })
}

const resetAnalysis = () => {
  streamingAnalysis.value = ''
  isStreaming.value = false
  startAIAnalysis();
}

const generateAnalysisPrompt = () => {
  const stats = fiveElementsResult.value.elementStats
  const maxElement = Object.entries(stats).reduce((a, b) => a[1].count > b[1].count ? a : b)
  const minElement = Object.entries(stats).reduce((a, b) => a[1].count < b[1].count ? a : b)
  
  return `请为${fiveElementsResult.value.personalInfo.name}进行详细的命理解析。\n` +
         `出生信息：阳历${fiveElementsResult.value.personalInfo.solarBirthday}，${fiveElementsResult.value.personalInfo.lunarBirthday}，${fiveElementsResult.value.personalInfo.zodiac}，${fiveElementsResult.value.personalInfo.constellation}\n` +
         `五行统计：${maxElement[0]}最旺(${maxElement[1].count}个)，${minElement[0]}最弱(${minElement[1].count}个)\n` +
         `五行分布：${fiveElementsResult.value.elementStats.金.count}个金，${fiveElementsResult.value.elementStats.木.count}个木，${fiveElementsResult.value.elementStats.水.count}个水，${fiveElementsResult.value.elementStats.火.count}个火，${fiveElementsResult.value.elementStats.土.count}个土\n` +
         `请从性格特点、事业发展、健康状况、人际关系、运势建议等方面进行详细分析，用通俗易懂的语言。`
}

// 在onUnmounted中清理资源
onUnmounted(() => {
  if (eventSource.value) {
    eventSource.value.close()
  }
})

function wuxing(hanzi) {
  console.log(hanzi);
  console.log(fiveElementsResult);
  return fiveElementsResult.value.mapHanZiToWuXing[hanzi]
}

// 修改calculateFiveElements函数
const calculateFiveElements = () => {
  if (!userData.name || !userData.birthYear || !userData.birthMonth || !userData.birthDay || !userData.birthHour) {
    // 检查用户输入是否完整

    console.warn('信息不完整，跳过计算')
    return
  }
    
  // 设置loading状态为true
  isLoading.value = true;
  const requestData = {
    name: userData.name,
    birthday: `${userData.birthYear}-${String(userData.birthMonth).padStart(2, '0')}-${String(userData.birthDay).padStart(2, '0')}`,
    birthdayType: calendarType.value,
    isLeapMonth: userData.isLeapMonth,
    shiChen: hourToBranch[userData.birthHour]
  }

  request.post('/wuxing/user', requestData).then(res => {
    const apiData = res.data;

    // 直接使用后端返回的五行映射
    const mapHanZiToWuXing = apiData.mapHanZiToWuXing || {};

    // 构建姓名五行数据（直接从映射中获取）
    const nameElements = [];
    for (const char of apiData.name) {
      const element = mapHanZiToWuXing[char];
      if (element) {
        nameElements.push({
          char: char,
          element: element
        });
      }
    }

    // 构建生辰八字数据
    const bazi = {
      yearStem: apiData.yearZodiac.charAt(0),
      yearBranch: apiData.yearZodiac.charAt(1),
      monthStem: apiData.monthZodiac.charAt(0),
      monthBranch: apiData.monthZodiac.charAt(1),
      dayStem: apiData.dayZodiac.charAt(0),
      dayBranch: apiData.dayZodiac.charAt(1),
      hourStem: apiData.shiZodiac.charAt(0),
      hourBranch: apiData.shiZodiac.charAt(1)
    };

    // 计算五行统计（使用mapHanZiToWuXing）
    const elementStats = calculateElementStatsFromApi(mapHanZiToWuXing, apiData.name, bazi);

    // 设置结果数据
    fiveElementsResult.value = {
      personalInfo: {
        name: apiData.name,
        solarBirthday: apiData.birthday,
        lunarBirthday: apiData.chineseBirthday,
        zodiac: apiData.chineseZodiac,
        constellation: apiData.constellation
      },
      nameElements: nameElements,
      bazi: bazi,
      elementStats: elementStats,
      mapHanZiToWuXing: mapHanZiToWuXing // 保存完整的五行映射
    };

        
    // 设置结果数据后，自动滚动到结果区域
    nextTick(() => {
      const resultSection = document.querySelector('.destiny-button');
      if (resultSection) {
        resultSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    });
  }).finally(() => {
    // 无论成功或失败，都关闭loading状态
    isLoading.value = false;
  });;
};

// 简化后的calculateElementStatsFromApi函数
const calculateElementStatsFromApi = (mapHanZiToWuXing, name, bazi) => {
  const stats = {};
  fiveElements.forEach(element => {
    stats[element] = {
      count: 0,
      nameCount: '',
      baziCount: 0
    };
  });

  // 统计姓名五行（直接从mapHanZiToWuXing获取）
  for (const char of name) {
    const element = mapHanZiToWuXing[char];
    if (element) {
      stats[element].count++;
      stats[element].nameCount=stats[element].nameCount+char;
    }
  }

  // 统计八字五行（直接从mapHanZiToWuXing获取）
  const baziChars = [
    bazi.yearStem, bazi.yearBranch,
    bazi.monthStem, bazi.monthBranch,
    bazi.dayStem, bazi.dayBranch,
    bazi.hourStem, bazi.hourBranch
  ];

  for (const char of baziChars) {
    const element = mapHanZiToWuXing[char];
    if (element) {
      stats[element].count++;
      stats[element].baziCount++;
    }
  }

  return stats;
};


// 修改流数据处理方法
const processStreamingData = (text) => {
  streamingAnalysis.value += text;

  // 自动滚动到底部
  nextTick(() => {
    const element = document.querySelector('.analysis-content');
    if (element) {
      element.scrollTop = element.scrollHeight;

      // 自动调整高度
      const contentHeight = element.scrollHeight;
      element.style.height = 'auto';
      element.style.minHeight = Math.min(contentHeight, 400) + 'px';
    }
  });
};

// 添加禁用状态提示信息
const disabledTooltip = computed(() => {
  if (isLoading.value) return '正在计算中，请稍候...';

  const messages = [];

  // 验证姓名
  if (!userData.name || !/^[\u4e00-\u9fa5]+$/.test(userData.name)) {
    messages.push('请输入有效的中文姓名');
  }

  // 验证年份
  const year = parseInt(userData.birthYear);
  if (!userData.birthYear || !Number.isFinite(year) || year < 1900 || year > 2100) {
    messages.push('年份必须在1900-2100之间');
  }

  // 验证月份
  const month = parseInt(userData.birthMonth);
  if (!userData.birthMonth || !Number.isFinite(month) || month < 1 || month > 12) {
    messages.push('月份必须在1-12之间');
  }

  // 验证日期
  const day = parseInt(userData.birthDay);
  if (!userData.birthDay || !Number.isFinite(day) || day < 1 || day > 31) {
    messages.push('日期必须在1-31之间');
  }

  // 验证时辰
  if (!userData.birthHour) {
    messages.push('请选择出生时辰');
  }

  return messages.length > 0 ? messages.join('\n') : '';
});



// 添加Markdown渲染方法
const renderMarkdown = (content) => {
  return md.render(content);
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.destiny-calculator {
  position: relative;
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 50%, #16213e 100%);
  overflow: hidden;
}

.cosmic-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.stars {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image:
    radial-gradient(2px 2px at 20px 30px, #ffd700, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255, 215, 0, 0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent),
    radial-gradient(1px 1px at 130px 80px, rgba(255, 255, 255, 0.8), transparent);
  background-repeat: repeat;
  background-size: 200px 150px;
  animation: twinkle 3s ease-in-out infinite alternate;
}

.taiji-watermark {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  height: 300px;
  background: linear-gradient(45deg, transparent 40%, rgba(255, 215, 0, 0.03) 50%, transparent 60%);
  border-radius: 50%;
  animation: rotate 30s linear infinite;
}

@keyframes twinkle {
  0% {
    opacity: 0.5;
  }

  100% {
    opacity: 1;
  }
}

@keyframes rotate {
  0% {
    transform: translate(-50%, -50%) rotate(0deg);
  }

  100% {
    transform: translate(-50%, -50%) rotate(360deg);
  }
}

.calculator-container {
  position: relative;
  z-index: 2;
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
}

.calculator-header {
  text-align: center;
  margin-bottom: 40px;
}

.destiny-title {
  font-family: 'KaiTi', serif;
  font-size: 2.5rem;
  color: #ffd700;
  margin-bottom: 10px;
  text-shadow: 0 0 20px rgba(255, 215, 0, 0.5);
  letter-spacing: 0.2em;
}

.destiny-subtitle {
  font-size: 1.2rem;
  color: rgba(255, 215, 0, 0.7);
  font-weight: 300;
  letter-spacing: 0.1em;
}

.input-section {
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 215, 0, 0.2);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  margin-bottom: 30px;
}

.input-group {
  margin-bottom: 25px;
}

.input-label {
  display: block;
  font-size: 1.1rem;
  color: #ffd700;
  margin-bottom: 8px;
  font-weight: 500;
}

.destiny-input,
.destiny-select {
  width: 100%;
  padding: 15px;
  background: rgba(0, 0, 0, 0.5);
  border: 1px solid rgba(255, 215, 0, 0.3);
  border-radius: 10px;
  color: #fff;
  font-size: 1.1rem;
  transition: all 0.3s ease;
}

/* 姓名五行优化样式 */
.name-elements-enhanced {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.name-header {
  text-align: center;
  margin-bottom: 15px;
}

.name-display {
  font-size: 2rem;
  color: #ffd700;
  font-weight: bold;
  margin-right: 15px;
}

.name-analysis {
  font-size: 1.2rem;
  color: rgba(255, 215, 0, 0.8);
}

.character-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  border: 1px solid rgba(255, 215, 0, 0.2);
}

.character {
  font-size: 2.5rem;
  color: #fff;
  font-weight: bold;
  margin-bottom: 8px;
}

.name-summary {
  text-align: center;
  margin-top: 15px;
  font-size: 1.1rem;
  color: #ffd700;
}

/* 五行统计表格优化样式 */
.element-char {
  font-size: 1.1rem;
  font-weight: bold;
  color: #ffd700;
}

.strength-rating {
  padding: 4px 12px;
  border-radius: 15px;
  font-weight: bold;
  font-size: 0.9rem;
}

.strength-rating.偏弱 {
  background: #90EE90;
  color: #000;
}

.strength-rating.适中 {
  background: #FFA500;
  color: #fff;
}

.strength-rating.偏强 {
  background: #FF6347;
  color: #fff;
}

/* 命理解析样式优化 */
.destiny-analysis {
  line-height: 1.8;
  color: #fff;
}

.destiny-analysis strong {
  color: #ffd700;
  font-weight: bold;
}

.destiny-input:focus,
.destiny-select:focus {
  outline: none;
  border-color: #ffd700;
  box-shadow: 0 0 15px rgba(255, 215, 0, 0.3);
}

.date-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.calendar-selector {
  display: flex;
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 215, 0, 0.3);
  border-radius: 10px;
  overflow: hidden;
}

.calendar-btn {
  flex: 1;
  padding: 15px;
  background: transparent;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  font-size: 1.1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.calendar-btn.active {
  background: rgba(255, 215, 0, 0.2);
  color: #ffd700;
  font-weight: bold;
}

.calendar-btn:hover {
  background: rgba(255, 215, 0, 0.1);
}

.calendar-divider {
  width: 1px;
  background: rgba(255, 215, 0, 0.3);
}

.btn-text {
  font-weight: 600;
}

.destiny-button {
  width: 100%;
  padding: 18px;
  background: linear-gradient(135deg, #8B4513, #D2691E);
  border: none;
  border-radius: 10px;
  color: #000;
  font-size: 1.2rem;
  font-weight: bold;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-top: 20px;
}

.destiny-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 215, 0, 0.4);
}

.button-glow {
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s ease;
}

.destiny-button:hover .button-glow {
  left: 100%;
}

.button-text {
  position: relative;
  z-index: 2;
}

/* 结果区域样式 */
.result-section {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.info-card,
.element-card,
.stats-card,
.analysis-card {
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 215, 0, 0.2);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.error-text {
  color: #ff4757;
  font-size: 12px;
  margin-top: 4px;
  font-weight: 500;
  animation: shake 0.3s ease-in-out;
}

@keyframes shake {

  0%,
  100% {
    transform: translateX(0);
  }

  25% {
    transform: translateX(-2px);
  }

  75% {
    transform: translateX(2px);
  }
}

.card-title {
  font-family: 'KaiTi', serif;
  font-size: 1.5rem;
  color: #ffd700;
  margin-bottom: 20px;
  text-align: center;
}

/* 个人信息样式 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-label {
  color: rgba(255, 215, 0, 0.8);
  font-weight: bold;
}

.info-value {
  color: #fff;
}

/* 姓名五行样式 */
.name-elements-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: center;
}

.name-element-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.character {
  font-size: 2rem;
  color: #fff;
  font-weight: bold;
}

.element-badge {
  padding: 4px 12px;
  border-radius: 15px;
  font-size: 0.9rem;
  font-weight: bold;
  color: #000;
}

.element-badge.金 {
  background: #FFD700;
}

.element-badge.木 {
  background: #90EE90;
}

.element-badge.水 {
  background: #87CEEB;
}

.element-badge.火 {
  background: #FF6347;
}

.element-badge.土 {
  background: #DEB887;
}

/* 生辰八字样式 */
.bazi-elements {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.bazi-row {
  display: flex;
  justify-content: space-around;
  gap: 20px;
}

.bazi-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.bazi-label {
  color: rgba(255, 215, 0, 0.8);
  font-weight: bold;
}

.bazi-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.bazi-char {
  font-size: 1.5rem;
  color: #fff;
  font-weight: bold;
}

/* 五行统计表格样式 */
.stats-table {
  overflow-x: auto;
}

.stats-table table {
  width: 100%;
  border-collapse: collapse;
}

.stats-table th,
.stats-table td {
  padding: 12px;
  text-align: center;
  border-bottom: 1px solid rgba(255, 215, 0, 0.2);
}

.stats-table th {
  color: #ffd700;
  font-weight: bold;
}

.element-name {
  font-weight: bold;
  color: #fff;
}

.count-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  background: rgba(255, 215, 0, 0.2);
  color: #ffd700;
  font-weight: bold;
}

.count-badge.total {
  background: rgba(255, 215, 0, 0.4);
}

.strength-badge {
  padding: 4px 12px;
  border-radius: 15px;
  font-weight: bold;
  font-size: 0.9rem;
}

.strength-badge.strong {
  background: #FF6347;
  color: #fff;
}

.strength-badge.moderate {
  background: #FFA500;
  color: #fff;
}

.strength-badge.weak {
  background: #90EE90;
  color: #000;
}


/* 命理解析样式优化 */
.analysis-content {
  color: #fff;
  line-height: 1.8;
  font-size: 1.1rem;
  text-align: left;
  overflow-y: auto;
  transition: height 0.3s ease;
  padding: 20px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  border: 1px solid rgba(255, 215, 0, 0.2);
}

/* Markdown内容样式 */
.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  color: #ffd700;
  margin: 1.5em 0 0.5em 0;
  border-bottom: 1px solid rgba(255, 215, 0, 0.3);
  padding-bottom: 0.3em;
}

.markdown-content p {
  margin: 1em 0;
  color: #e0e0e0;
}

.markdown-content strong {
  color: #ffd700;
  font-weight: bold;
}

.markdown-content em {
  color: #90EE90;
  font-style: italic;
}

.markdown-content ul,
.markdown-content ol {
  margin: 1em 0;
  padding-left: 2em;
}

.markdown-content li {
  margin: 0.5em 0;
  color: #e0e0e0;
}

.markdown-content blockquote {
  border-left: 4px solid #ffd700;
  padding-left: 1em;
  margin: 1.5em 0;
  color: #b0b0b0;
  font-style: italic;
}

.markdown-content code {
  background: rgba(255, 215, 0, 0.1);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  color: #ffd700;
  font-family: 'Courier New', monospace;
}

.markdown-content pre {
  background: rgba(0, 0, 0, 0.3);
  padding: 1em;
  border-radius: 5px;
  overflow-x: auto;
  margin: 1.5em 0;
}

.markdown-content pre code {
  background: transparent;
  padding: 0;
  color: #e0e0e0;
}

.markdown-content table {
  width: 100%;
  border-collapse: collapse;
  margin: 1.5em 0;
}

.markdown-content th,
.markdown-content td {
  border: 1px solid rgba(255, 215, 0, 0.3);
  padding: 0.5em;
  text-align: left;
}

.markdown-content th {
  background: rgba(255, 215, 0, 0.1);
  color: #ffd700;
  font-weight: bold;
}

.markdown-content a {
  color: #87CEEB;
  text-decoration: none;
}

.markdown-content a:hover {
  text-decoration: underline;
  color: #ffd700;
}

/* 自动高度调整 */
.analysis-content.auto-height {
  height: auto;
  min-height: 100px;
  max-height: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .analysis-content {
    padding: 15px;
    font-size: 1rem;
  }

  .markdown-content h1 {
    font-size: 1.3em;
  }

  .markdown-content h2 {
    font-size: 1.2em;
  }

  .markdown-content h3 {
    font-size: 1.1em;
  }
}


/* 响应式设计 */
@media (max-width: 768px) {
  .date-grid {
    grid-template-columns: 1fr;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .destiny-title {
    font-size: 2rem;
  }

  .calculator-container {
    padding: 20px 10px;
  }

  .input-section,
  .info-card,
  .element-card,
  .stats-card,
  .analysis-card {
    padding: 20px;
  }

  @media (max-width: 480px) {

  .stats-card{
    padding:8px;
  }
}

  .bazi-row {
    flex-direction: row; /* 改为横向排列 */
    flex-wrap: wrap; /* 允许换行 */
    gap: 10px; /* 减小间距 */
  }
  
  .bazi-cell {
    flex: 1; /* 均分空间 */
    min-width: 45%; /* 确保每个柱子有足够的空间 */
  }
}

.element-pair {
  display: flex;
  gap: 5px;
  flex-direction: column;
  align-items: center;
}

.name-chars {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
  justify-content: center;
}

.char-badge {
  padding: 2px 6px;
  border-radius: 8px;
  background: rgba(255, 215, 0, 0.2);
  color: #ffd700;
  font-size: 0.9rem;
  border: 1px solid rgba(255, 215, 0, 0.3);
}

.bazi-columns {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.bazi-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9rem;
}

.column-label {
  color: #ffd700;
  font-weight: bold;
  min-width: 40px;
}

.bazi-char {
  font-weight: bold;
  color: #fff;
  min-width: 30px;
}

.element-tags {
  display: flex;
  gap: 4px;
}

.bazi-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.bazi-char {
  font-size: 1.2rem;
  font-weight: bold;
  color: #ffd700;
}

.element-tags {
  display: flex;
  gap: 2px;
  flex-wrap: wrap;
  justify-content: center;
}

.element-badge {
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 0.75rem;
  color: #000;
  font-weight: bold;
}


.stats-table table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.stats-table th,
.stats-table td {
  padding: 12px 8px;
  text-align: center;
  border-bottom: 1px solid rgba(255, 215, 0, 0.2);
}

.stats-table th {
  background: rgba(255, 215, 0, 0.1);
  color: #ffd700;
  font-weight: bold;
}

.stats-table td {
  color: #fff;
}

.count-text {
  font-size: 1.1rem;
  font-weight: bold;
  color: #ffd700;
}

.total-count {
  font-size: 1.2rem;
  font-weight: bold;
  color: #ffd700;
}

.strength-bar {
  position: relative;
  width: 100%;
  height: 20px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  background: linear-gradient(90deg, #ffd700, #ffed4e);
  border-radius: 10px;
  transition: width 0.3s ease;
}

.strength-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 0.8rem;
  font-weight: bold;
  color: #000;
}

.element-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
  font-weight: bold;
}

.element-badge.金 { background: #f0f0f0; color: #333; }
.element-badge.木 { background: #4caf50; color: #fff; }
.element-badge.水 { background: #2196f3; color: #fff; }
.element-badge.火 { background: #ff5722; color: #fff; }
.element-badge.土 { background: #ff9800; color: #fff; }

.ai-analysis-btn {
  width: 100%;
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 10px;
  color: white;
  font-size: 1.1rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.ai-analysis-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.ai-analysis-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.ai-analysis-btn.secondary {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  margin-top: 20px;
}

.streaming-indicator {
  text-align: center;
  padding: 20px;
  color: #ffd700;
}

.typing-animation {
  display: inline-block;
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.streaming-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 20px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  border: 1px solid rgba(255, 215, 0, 0.2);
  line-height: 1.8;
  color: #fff;
  text-align: left; /* 改为右对齐 */
  direction: ltr;
}

.typing-text {
  white-space: pre-wrap;
  word-wrap: break-word;
}

.typing-text strong {
  color: #ffd700;
  font-weight: bold;
}


.loading {
  opacity: 0.8;
  cursor: not-allowed !important;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-left: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.destiny-button.loading {
  animation: pulse 1.5s ease-in-out infinite;
}

/* 持续闪烁动画 */
@keyframes pulse-glow {
  0% {
    box-shadow: 0 0 5px rgba(255, 215, 0, 0.5);
  }
  50% {
    box-shadow: 0 0 20px rgba(255, 215, 0, 0.8), 0 0 30px rgba(255, 215, 0, 0.6), 0 0 40px rgba(255, 215, 0, 0.4);
  }
  100% {
    box-shadow: 0 0 5px rgba(255, 215, 0, 0.5);
  }
}

.destiny-button.pulsing {
  animation: pulse-glow 2s ease-in-out infinite;
}

.destiny-button.pulsing .button-glow {
  animation: pulse-glow 2s ease-in-out infinite;
}

/* 确保loading状态下不闪烁 */
.destiny-button.loading {
  animation: none;
}

.destiny-button.loading .button-glow {
  animation: none;
}

.destiny-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
  pointer-events: auto;
    /* 添加这一行确保tooltip显示 */
}

.destiny-button:disabled:hover {
  transform: none;
  box-shadow: none;
}

.destiny-button:disabled .button-glow {
  display: none;
}

.destiny-button[title] {
  position: relative;
}

.destiny-button[title]:hover::after {
  content: attr(title);
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  white-space: pre-line;
  z-index: 1000;
  min-width: 200px;
  text-align: center;
  pointer-events: none;
  transition-delay: 0s !important;
  /* 立即显示 */
}

/* 确保原生title不显示 */
.destiny-button[title]:hover {
  overflow: visible;
}
</style>
